import json
from django.shortcuts import render
from django.http import JsonResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q
from django.views.decorators.clickjacking import xframe_options_exempt
from .models import User, Role


# 用户视图
# Create your views here.
@xframe_options_exempt
def index(request):
    return render(request, "user/index.html")


def user_list(request):
    result = {"status": 1, "msg": "操作失败！"}
    data = request.GET
    try:
        page = data.get("page", 1)
        limit = data.get("limit", 5)
        search = data.get("search")
        users = User.objects.filter(is_delete=0)
        if search and search != "":
            users = users.filter(Q(name__icontains=search) | Q(phone=search))
        user_count = users.count()
        paginator = Paginator(users.order_by("-create_time"), limit)     # 每页多少条数据
        try:
            users = paginator.page(page)        # 返回 page（页数）的数据
        except PageNotAnInteger:
            users = paginator.page(1)           # 第一页
        except EmptyPage:
            users = paginator.page(paginator.num_pages)  # 最后一页
        data_list = []
        for i in range(len(users)):

            data_list.append({
                "No": i+1,
                "id": users[i].id,
                "name": users[i].name,
                "id_card": users[i].id_card,
                "phone": users[i].phone,
                "status": users[i].status,
                "remark": users[i].remark,
                "create_time": str(users[i].create_time).split(".")[0],
            })

        result["data"] = data_list
        result["data_count"] = user_count
        result["status"] = 0    # layui parseData status=0 才认为是成功
        result["msg"] = "用户列表查询成功！"
    except Exception as e:
        print(e)
    return JsonResponse(result)


@xframe_options_exempt
def user_add(request):
    if request.method == "POST":
        result = {"status": 0, "msg": "操作失败！"}
        data = json.loads(request.body)
        user_id = request.session.get("user_id")
        try:
            print(data)
            name = data.get("name")
            phone = data.get("phone")
            id_card = data.get("id_card")
            password = data.get("password")
            remark = data.get("remark")
            user_exist = User.objects.filter(id_card=id_card).count()
            if user_exist > 0:
                result["msg"] = "当前身份证号码已存在，请更换身份证号码！"
                return JsonResponse(result)
            user_exist_count = User.objects.filter(phone=phone).count()
            if user_exist_count > 0:
                result["msg"] = "当前手机号已存在，请更换手机号！"
                return JsonResponse(result)
            new_user = User(name=name, phone=phone, password=password, remark=remark, id_card=id_card, creator_id=user_id)
            new_user.save()
            result["status"] = 1
            result["msg"] = "添加用户成功！"
        except Exception as e:
            print(e)
        return JsonResponse(result)
    else:
        roles = Role.objects.filter(is_delete=0).all()
        return render(request, "user/add.html", {"roles": roles})


@xframe_options_exempt
def user_edit(request, user_id=None):
    if request.method == "POST":
        result = {"status": 0, "msg": "操作失败！"}
        data = json.loads(request.body)
        try:
            print(data)
            name = data.get("name")
            phone = data.get("phone")
            id_card = data.get("id_card")
            password = data.get("password")
            remark = data.get("remark")
            user = User.objects.filter(id=int(user_id), is_delete=0).first()
            if not user:
                result["msg"] = "该用户不存在！"
                return JsonResponse(result)
            if user.id_card != id_card:
                id_card_exist = User.objects.filter(~Q(id=int(user_id)), id_card=id_card, is_delete=0).first()
                if id_card_exist:
                    result["msg"] = "该身份证号码已被占用，请更换身份证号码!"
                    return JsonResponse(result)
                user.id_card = id_card
            if user.phone != phone:
                phone_exist = User.objects.filter(~Q(id=int(user_id)), phone=phone, is_delete=0).first()
                if phone_exist:
                    result["msg"] = "该手机号已被占用，请更换手机号!"
                    return JsonResponse(result)
                user.phone = phone
            if user.name != name:
                user.name = name
            if user.password != password:
                user.password = password
            if user.remark != remark:
                user.remark = remark
            user.save()
            result["status"] = 1
            result["msg"] = "用户信息更新成功!"
        except Exception as e:
            print(e)
        return JsonResponse(result)
    else:
        user = User.objects.filter(id=int(user_id), is_delete=0).first()
        return render(request, "user/edit.html", {'user': user})


def user_delete(request, user_id):
    result = {"status": 0, "msg": "操作失败！"}
    if request.method == "DELETE":
        try:
            user = User.objects.filter(id=int(user_id), is_delete=0).first()
            if user:
                user.is_delete = 1
                user.save()
                result["status"] = 1
                result["msg"] = "用户删除成功!"
            else:
                result["msg"] = "请确认用户是否存在!"
        except Exception as e:
            print(e)
    return JsonResponse(result)


def user_status(request, user_id):
    result = {"status": 0, "msg": "操作失败！"}
    if request.method == "POST":
        data = json.loads(request.body)
        try:
            print(data)
            status = data.get("status", None)
            if status is None or not isinstance(status, bool):
                result["msg"] = "请确认操作类型!"
                return JsonResponse(result)

            user = User.objects.filter(id=int(user_id), is_delete=0).first()
            if user:
                if status is True and user.status == 0:
                    user.status = 1
                if status is False and user.status == 1:
                    user.status = 0
                user.save()
                result["status"] = 1
                result["msg"] = "用户启用成功!" if status is True else "用户禁用成功！"
            else:
                result["msg"] = "请确认用户是否存在!"
        except Exception as e:
            print(e)
    return JsonResponse(result)
